#include "collection.h"

#include <QDir>
#include <QtDebug>

#include "taglib/fileref.h"
#include "taglib/tag.h"

using namespace Playur;

Playur::Collection::Collection()
{

}

void Playur::Collection::addFolder(const QString& path)
{
    folders.append(path);
}

void Playur::Collection::scan()
{
    foreach(QString folder, folders)
    {
        recurseInto(QDir(folder));
    }
}

void Collection::recurseInto(const QDir& dir)
{
    qDebug() << "Reading dir" << dir.absolutePath();
    
    QFileInfoList files = dir.entryInfoList();
    foreach(QFileInfo info, files)
    {
	if (info.isDir() && !info.fileName().startsWith("."))
            recurseInto(info.absoluteFilePath());
	  qDebug() << info.absoluteFilePath() << info.fileName();
	    
        if (info.isFile() && info.isReadable())
            if (info.fileName().endsWith(".mp3") ||
                    info.fileName().endsWith(".wma") ||
                    info.fileName().endsWith(".ogg"))
                addTrack(info.absoluteFilePath());
    }
}

void Collection::addTrack(const QString& path)
{
    TagLib::FileRef f(path.toAscii().data());

    TrackInfo ti;
    ti.album = QString(f.tag()->artist().toCString());
    ti.artist = QString(f.tag()->album().toCString());
    ti.title = QString(f.tag()->title().toCString());
    ti.index = f.tag()->track();
    ti.filename = path;
    ti.id = tracks.size() + 1;
    ti.urlBase = "http://127.0.0.1:3530/get/";

    tracks.append(ti);
}

QString Collection::getTrackPath(int id)
{
  qDebug() << "Collection: request for track" << id;
  return tracks[id-1].filename;
}

QString Collection::nickname()
{
  return _nickname;
}

void Collection::setNickname(const QString& nickname)
{
  _nickname = nickname;
}

Playur::Collection::~Collection()
{

}

QString Playur::Collection::url()
{
  return _url;
}

void Playur::Collection::setUrl(const QString& url)
{
  _url = url;
}

const QString& Playur::Collection::xml()
{
    updateXml();
    return _xml;
}


#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include "../qt_serialize.h"
#include <string>
#include <sstream>

void Playur::Collection::updateXml()
{
    qDebug() << "called updateXml()";
    qDebug() << "Collection has " << tracks.count() << " items";

    std::stringstream ss;

    boost::archive::xml_oarchive archive(ss);
    archive << boost::serialization::make_nvp("collection", (*this));

    _xml.clear();
    _xml.append(QString::fromStdString(ss.str()));
}